// 用户路由
const express = require("express");
const router = express.Router();
// hash密码
const bcrypt = require("bcrypt");
// 工具
const _ = require("lodash");
// 对客户端发送过来的数据进行校验
const Joi = require("joi");

const path = require("path");
const dirname = path.resolve();
const { User, userRules, validateUser } = require(path.join(
  dirname,
  "src/model/user"
));

// 创建用户
router.post("/create", async (req, res) => {
  const { error } = validateUser(req.body);
  if (error) return res.status(400).send({ message: error.message });

  // 查询用户是否存在
  const isExist = await User.findOne({ email: req.body.email });
  if (isExist) return res.status(400).send({ message: "邮箱已经被注册" });

  // 生成盐，并使用盐对密码进行加密
  const salt = await bcrypt.genSalt(10);
  req.body.password = await bcrypt.hash(req.body.password, salt);

  // 创建用户
  const user = await new User(req.body).save();
  res.send({
    data: _.pick(user, ["_id", "email", "username", "avatar"]),
  });
});

// 修改用户信息
router.put("/modify", async (req, res) => {
  req.body = _.pick(req.body, ["username", "avatar", "_id"]);

  const schema = _.pick(userRules, ["username"]);
  const { error } = Joi.validate(req.body, schema, {
    // 允许对象包含被忽略的未知键
    allowUnknown: true,
  });
  if (error) return res.status(400).send({ message: error.message });

  // new: true 返回修改后的文档 默认值为false 返回原始文档
  // fields: '-password' 从返回值中抛除密码字段
  const user = await User.findByIdAndUpdate(
    req.body._id,
    { $set: req.body },
    { new: true, useFindAndModify: false, fields: "-password" }
  );
  res.send(user);
});

// 修改用户密码
router.put("/modifyPassword", async (req, res) => {
  req.body = _.pick(req.body, ["oldPassword", "password", "email"]);
  const { oldPassword, password, email } = req.body;

  const schema = _.pick(userRules, ["password"]);

  await User.findOne({ email }).then(async (result) => {
    // 如果用户输入的密码和原始密码一致
    if (!bcrypt.compareSync(oldPassword, result.password)) {
      return res.status(400).send({ message: "原始密码输入错误" });
    }

    const { error } = Joi.validate(req.body, schema, {
      // 允许对象包含被忽略的未知键
      allowUnknown: true,
    });
    // 数据格式没有通过验证
    if (error) return res.status(400).send({ message: error.message });

    // 更新密码
    const salt = await bcrypt.genSalt(10);
    const finalPassword = await bcrypt.hash(password, salt);
    await User.findByIdAndUpdate(
      result._id,
      { $set: { password: finalPassword } },
      { useFindAndModify: false }
    );
    res.send({ message: "密码修改成功" });
  });
});

// 根据 query 获取用户列表
router.get("", async (req, res) => {
  const query = req.query.query;
  const queryReg = new RegExp(query, "gi");
  const users = await User.find({
    username: queryReg,
  }).limit(10);

  const result = users.map((item) =>
    _.pick(item, ["username", "email", "avatar"])
  );
  res.send({ data: result, message: "获取用户列表成功" });
});

// 导出路由
module.exports = router;
